package cn.zxl.spring.holiday.job.web.controller;

import cn.zxl.spring.holiday.job.domain.Employee;
import cn.zxl.spring.holiday.job.web.json.JsonResult;
import cn.zxl.spring.holiday.job.web.log.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Date 2021/10/1 12:32
 * @Version 1.0
 * @Description
 */
@Controller
public class LoginController {


    @ResponseBody
    @Log(title = "用户登录")
    @RequestMapping("/login")
    public JsonResult login(String username, String password, HttpSession session){
        JsonResult jsonResult = new JsonResult();
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            Employee employee = (Employee) subject.getPrincipal();
            session.setAttribute("SESSION_USER", employee);
            jsonResult.setMsg("登录成功");
            return jsonResult;
        } catch (UnknownAccountException ue) {
            ue.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("账号不存在");
            return jsonResult;
        } catch (IncorrectCredentialsException ie) {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("账号密码错误");
            return jsonResult;
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("系统繁忙");
            return jsonResult;
        }
    }

}
